<?php
/**
 * Created by PhpStorm.
 * User: 董坤鸿
 * Date: 2017/1/10
 * Time: 16:44
 */

namespace App\Services\Statistics;

use App\Models\Company;
use App\Models\Project;
use App\Models\WxClient;
use App\Plugins\Wechat\Messages;
use App\Plugins\Wechat\SETTING;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use MongoDB\BSON\UTCDateTime;

class BaseService
{

    /**
     * 渠道列表
     * @return
     */
    public function getCompaniesList()
    {
        $minutes = 1;
        $companies = Cache::remember('companies', $minutes, function() {
            return $this->getCompanies();
        });
        return $companies;

    }

    /**
     * 获取渠道统计数据
     * @return mixed
     */
    public function getCompanies(){
        $companies = Company::withTrashed()->get();
        $lists = $companies->map(function($company){
            $results = new CompaniesFieldService();
            //序号
            $results->company_id = $company->_id;
            //企业名称
            $results->name = $company->name;
            //开始时间
            $results->startDate = $company->startDate ? date('Y-m-d H:s:i', $company->startDate->getTimestamp()) : null;
            //结束时间
            $results->endDate = $company->endDate ? date('Y-m-d H:s:i', $company->endDate->getTimestamp()) : null;
            //获取帐号数量
            $results->accountCount = $this->getAccountCount($results->company_id);
            //获取微信总数
            $results->wxClientCount = $this->getWxClientCount($results->company_id);
            //获取已用微信数
            $results->projectCount = $this->getProjectCount($results->company_id);
            //获取未使用微信数
            $results->unusedCount = $this->getUnusedCount($results->company_id);
            //获取好友数量
            $results->contactNum = $this->getContactNum($results->company_id);
            //获取对话客户数
            $results->dialogueNum = $this->getDialogueNum($results->company_id);
            //获取发送消息
            $results->sendMsgCount = $this->getSendMsgCount($results->company_id);
            //获取好友消息数
            $results->getMsgCount = $this->getMsgCount($results->company_id);
            //获取标签数量
            $results->tagCount = $this->getTagCount($results->company_id);
            //删除时间
            $results->deleted_at = $company->deleted_at ? date('Y-m-d H:s:i', $company->deleted_at->getTimestamp()) : null;
            return $results;
        });
        return $lists;
    }

    /**
     * 获取帐号数量
     * @param $company_id
     * @return int
     */
    public function getAccountCount(&$company_id)
    {
        $accountCount = 0;
        $groups = DB::table('groups')->where(['company_id' => $company_id, 'children' => ['$exists' => true, '$size' => 0]])->get()->toArray();
        if (!empty($groups)) {
            $groupId = array_map(function ($v) {
                return (string)$v['_id'];
            }, $groups);
        }
        if (!empty($groupId)) {
            $project = Project::whereIn('group_id', $groupId)->where(['wx_id' => ['$exists' => true, '$not' => ['$size' => 0]]])->pluck('users');
            $accountCount = count(array_unique(array_collapse($project)));
        }
        return $accountCount;
    }

    /**
     * 获取微信总数
     * @param $company_id
     */
    public function getWxClientCount(&$company_id)
    {
        $wxClientCount = WxClient::where('company_id', $company_id)->count();
        return $wxClientCount;
    }

    /**
     * 获取已用微信数
     * @param $company_id
     * @return mixed
     */
    public function getProjectCount(&$company_id)
    {
        $results = Company::find($company_id);
        if ($results) {
            return $results->projectCount;
        }
    }

    /**
     * 获取未使用微信数
     * @param $company_id
     * @return mixed
     */
    public function getUnusedCount(&$company_id)
    {
        $unusedCount = WxClient::where(['company_id' =>$company_id, 'project_id' => ''])->count();
        return $unusedCount;
    }

    /**
     * 获取好友数量
     * @param $company_id
     * @return int
     */
    public function getContactNum(&$company_id)
    {
        $wxClient = WxClient::where(['company_id' => $company_id])->get();
        $contactNum = 0;
        foreach ($wxClient as $key => $value) {
            $contactNum += count($value->contacts);
        }

        return $contactNum;
    }

    /**
     * 获取对话客户数
     * @param $company_id
     * @return int
     */
    public function getDialogueNum(&$company_id)
    {
        $wxClient = WxClient::where(['company_id' => $company_id])->get();
        $dialogueNum = 0;
        foreach ($wxClient as $key => $value) {
            $uin = $value->uin;
            $contacts = $value->contacts;
            if (!empty($contacts)) {
                foreach ($contacts as $k => $v) {
                    //发送消息客户数
                    $sendResult = DB::table('message_logs')->where(['to'=>$v['customer_id']])->count();
                    if($sendResult){
                        $dialogueNum++;
                    }else{
                        //接收消息客户数
                        $filters = [
                            'type' => ['$in' => SETTING::MAP_MSG_TYPE],
                            'from' => ['$in' => [$v['account'], $v['nickName']]],
                        ];
                        $messageHandler = new Messages($uin);
                        $receiveResult = $messageHandler->isMessage($filters);
                        if($receiveResult){
                            $dialogueNum++;
                        }
                    }
                }
            }

        }
        return $dialogueNum;
    }

    /**
     * 获取发送消息
     * @param $company_id
     * @return int
     */
    public function getSendMsgCount(&$company_id)
    {
        $wxClient = WxClient::where(['company_id' => $company_id])->get();
        $sendMsgCount = 0;
        foreach ($wxClient as $key => $value) {
            $contacts = $value->contacts;
            if (!empty($contacts)) {
                foreach ($contacts as $k => $v) {
                    $sendMsgCount += DB::table('message_logs')->where(['to' => $v['customer_id']])->count();
                }
            }
        }
        return $sendMsgCount;
    }

    /**
     * 获取好友消息数
     * @param $company_id
     * @return int
     */
    public function getMsgCount(&$company_id)
    {
        $wxClient = WxClient::where(['company_id' => $company_id])->get();
        $msgCount = 0;
        foreach ($wxClient as $key => $value) {
            $uin = $value->uin;
            $contacts = $value->contacts;
            if (!empty($contacts)) {
                foreach ($contacts as $k => $v) {
                    //接收消息客户数
                    $filters = [
                        'type' => ['$in' => SETTING::MAP_NORMAL_MSG],
                        'from' => ['$in' => [$v['account'], $v['nickName']]],
                    ];
                    $messageHandler = new Messages($uin);
                    $msgCount += $messageHandler->isMessage($filters);

                }
            }
        }
        return $msgCount;
    }

    /**
     * 获取标签数量
     * @param $company_id
     * @return int
     */
    public function getTagCount(&$company_id)
    {
        $customers = DB::table('customers')->where(['company_id' => $company_id])->get();
        $tagCount = 0;
        foreach ($customers as $key => $value) {
            if(isset($value['tags'])){
                $tagCount += count($value['tags']);
            }
        }
        return $tagCount;
    }

}